import * as htmlDocx from 'html-docx-js/dist/html-docx'

export async function exportToWord(containerSelectors, fileName, scaleIds) {
    const imgDatas = await generateImageDatas(containerSelectors, scaleIds)

    // Generate Word document
    const content = imgDatas
    const converted = htmlDocx.asBlob(content)
    const blob = new Blob([converted], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' })
    const link = document.createElement('a')
    link.href = window.URL.createObjectURL(blob)
    link.download = fileName
    link.click()
}

async function generateImageDatas(containerSelectors, scaleIds) {
    let imgDatas = ''
    const promises = containerSelectors.flatMap((selector, index) => {
        const containers = document.querySelectorAll(selector)
        return Array.from(containers).map(async (container, containerIndex) => {
            const shouldScale = shouldScaleChart(container.id, scaleIds)
            const targetSize = {
                width: container.offsetWidth,
                height: container.offsetHeight
            }
            const elements = container.querySelectorAll('svg, canvas')

            try {
                const base64Data = await getBase64Sync(elements[0].toDataURL('image/png'), targetSize, shouldScale)
                imgDatas += `<img src="${base64Data}" /><br>`
                return Promise.resolve()
            } catch (error) {
                return Promise.reject(error)
            }
        })
    })

    await Promise.all(promises.flat())
    return imgDatas
}

export function shouldScaleChart(containerId, scaleIds) {
    // 根据图表容器的ID来决定是否应该缩放图表
    return scaleIds.includes(containerId)
}

export async function getBase64Sync(imgUrl, targetSize, shouldScale) {
    return new Promise((resolve, reject) => {
        const image = new Image()
        image.src = imgUrl
        image.setAttribute('crossOrigin', '*')
        image.onload = function () {
            const canvas = document.createElement('canvas')
            const context = canvas.getContext('2d')

            if (shouldScale) {
                const scale = Math.min(targetSize.width / image.width, targetSize.height / image.height)
                const scaledWidth = image.width * scale * 0.5
                const scaledHeight = image.height * scale * 0.9
                canvas.width = scaledWidth
                canvas.height = scaledHeight
                const leftShift = 40 // Adjust this value as needed
                context.drawImage(image, -leftShift, 0, scaledWidth, scaledHeight)
            } else {
                canvas.width = image.width
                canvas.height = image.height
                const leftShift = 40
                context.drawImage(image, -leftShift, 0)
            }

            const dataurl = canvas.toDataURL('image/png')
            resolve(dataurl)
        }
    })
}
